<template>
  <div class="fee-manage">
    <!-- 搜索栏 -->
    <div class="search-box">
      <el-form :model="searchForm" inline>
        <el-form-item label="费用类型" v-if="isAdmin">
          <el-select v-model="searchForm.feeType" placeholder="请选择" clearable>
            <el-option label="团费" :value="2" v-if="userInfo.userType === 2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="年份">
          <el-input v-model="searchForm.year" placeholder="请输入年份"/>
        </el-form-item>
        <el-form-item label="月份">
          <el-input v-model="searchForm.month" placeholder="请输入月份"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button v-if="isAdmin" type="primary" @click="handleAdd">发布</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData.list" v-loading="loading">
      <el-table-column prop="feeType" label="费用类型">
        <template #default="scope">
          {{ scope.row.feeType === 1 ? '党费' : '团费' }}
        </template>
      </el-table-column>
      <el-table-column prop="year" label="年份"/>
      <el-table-column prop="month" label="月份"/>
      <el-table-column prop="amount" label="金额"/>
      <el-table-column prop="paymentMethod" label="缴费方式" v-if="!isAdmin">
        <template #default="scope">
          {{ scope.row.paymentMethod === 1 ? '支付宝' : '微信' }}
        </template>
      </el-table-column>
      <el-table-column prop="publisherName" label="发布人"/>
      <el-table-column prop="publishTime" label="发布时间"/>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button v-if="!isAdmin"
                     type="primary"
                     @click="handlePay(scope.row)">缴费
          </el-button>
          <el-button v-else type="primary" @click="handleDelete(scope.row)">删除</el-button>
          <el-tag v-if="scope.row.paymentStatus === 1 && scope.row.userId === userInfo.id && !isAdmin" type="success">已缴费</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="tableData.pageNum"
          v-model:page-size="tableData.pageSize"
          :total="tableData.total"
          @current-change="loadData"
          @size-change="loadData"/>
    </div>

    <!-- 发布对话框 -->
    <el-dialog v-model="publishDialog.visible" title="发布缴费信息">
      <el-form
          :model="publishForm"
          :rules="publishRules"
          ref="publishFormRef"
          label-width="80px">
        <el-form-item label="费用类型" prop="feeType">
          <el-select v-model="publishForm.feeType" placeholder="请选择">
            <el-option label="团费" :value="2" v-if="userInfo.userType === 1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model.number="publishForm.year"/>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-input v-model.number="publishForm.month"/>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model.number="publishForm.amount"/>
        </el-form-item>
        <!-- 上传收款码 -->
        <el-form-item label="收款码" prop="paymentCode">
          <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-success="handleFileUpload"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false">
            <el-button type="primary" icon="el-icon-upload2">点击上传收款码</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="publishDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handlePublish">确定</el-button>
      </template>
    </el-dialog>

    <!-- 缴费对话框 -->
    <el-dialog v-model="payDialog.visible" title="缴费">
      <el-form :model="payForm" label-width="80px">
        <el-form-item label="支付方式">
          <el-select v-model="payForm.paymentMethod" placeholder="请选择">
            <el-option label="微信" :value="2"/>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 显示收款码图片 -->
      <el-image
          v-if="payForm.paymentMethod === 2"
          :src="payForm.paymentCode"
          fit="contain"
          alt="收款码图片"
          style="max-width: 30%; max-height: 300px; margin-top: 20px;"
      ></el-image>
      <template #footer>
        <el-button @click="payDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handlePaySubmit">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import request from '@/utils/request'
import {getUserInfo} from "@/utils/auth";

const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload"
const userInfo = getUserInfo() || {}
const isAdmin = ref([1, 2].includes(userInfo.userType))

const loading = ref(false)
const searchForm = reactive({
  feeType: null,
  year: null,
  month: null
})

const tableData = reactive({
  list: [],
  total: 0,
  pageNum: 1,
  pageSize: 10
})

const publishDialog = reactive({
  visible: false
})

const publishForm = reactive({
  feeType: null,
  year: null,
  month: null,
  amount: null,
  paymentCode: null
})

const payDialog = reactive({
  visible: false
})

const payForm = reactive({
  id: null,
  paymentMethod: null
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      userId: userInfo.id,
      userType: userInfo.userType,
      pageNum: tableData.pageNum,
      pageSize: tableData.pageSize
    }

    if ([4, 5].includes(userInfo.userType)) {
      delete params.feeType
    }

    const res = await request.get('/fee/page', {params})
    if (res.code === '200') {
      tableData.list = res.data.list
      tableData.total = res.data.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}
const publishFormRef = ref(null)
// 打开发布对话框
const handleAdd = () => {
  // 重置表单
  Object.assign(publishForm, {
    feeType: null,
    year: new Date().getFullYear(), // 默认当前年份
    month: new Date().getMonth() + 1, // 默认当前月份
    amount: null
  })
  publishDialog.visible = true
}

// 表单验证规则
const publishRules = {
  feeType: [
    {required: true, message: '请选择费用类型', trigger: 'change'}
  ],
  year: [
    {required: true, message: '请输入年份', trigger: 'blur'},
    {type: 'number', message: '年份必须为数字', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value < 2000 || value > 2100) {
          callback(new Error('请输入有效的年份'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  month: [
    {required: true, message: '请输入月份', trigger: 'blur'},
    {type: 'number', message: '月份必须为数字', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value < 1 || value > 12) {
          callback(new Error('请输入有效的月份(1-12)'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  amount: [
    {required: true, message: '请输入金额', trigger: 'blur'},
    {type: 'number', message: '金额必须为数字', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('金额必须大于0'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  paymentCode: [
    {required: true, message: '请上传收款码', trigger: 'change'},
    {
      validator: (rule, value, callback) => {
        // 验证文件大小
        if (value && value.size / 1024 / 1024 > 2) { // 限制为 2MB
          callback(new Error('上传收款码大小不能超过 2MB'));
        } else {
          callback();
        }
      }, trigger: 'change'
    }
  ]
};

// 修改发布方法，添加表单验证
const handlePublish = async () => {
  if (!publishFormRef.value) return

  try {
    await publishFormRef.value.validate()

    await request.post('/fee/publish', {
      ...publishForm,
      publisherId: userInfo.id
    })

    ElMessage.success('发布成功')
    publishDialog.visible = false
    await loadData()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      console.error('发布失败:', error)
      ElMessage.error('发布失败')
    }
  }
}
// 打开缴费对话框
const handlePay = (row) => {
  payForm.id = row.id
  payForm.paymentMethod = null
  payForm.paymentCode = row.paymentCode
  payDialog.visible = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await request.delete(`/fee/delete/${row.id}`).then(res => {
      if(res.code === '200') {
        ElMessage.success('操作成功')
        payDialog.visible = false
        loadData()
      }
    })
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 提交缴费
const handlePaySubmit = async () => {
  try {
    await request.post(`/fee/pay/${payForm.id}`, null, {
      params: {
        userId: userInfo.id,
        paymentMethod: payForm.paymentMethod
      }
    })
    ElMessage.success('缴费成功')
    payDialog.visible = false
    await loadData()
  } catch (error) {
    console.error('缴费失败:', error)
    ElMessage.error('缴费失败')
  }
}

const handleFileUpload = (response) => {
  if (response.code === "200") {
    publishForm.paymentCode = response.data
    ElMessage.success("收款码上传成功")
  } else {
    ElMessage.error("收款码上传失败")
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png"
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error("收款码只能是 JPG 或 PNG 格式!")
  }
  if (!isLt2M) {
    ElMessage.error("收款码大小不能超过 2MB!")
  }
  return isJPG && isLt2M
}
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.fee-manage {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
